<!-- views/sales/components/SalesOrderOperationDialog.vue -->
<template>
  <el-dialog
    v-model="visible"
    :title="dialogTitle"
    width="800px"
    :before-close="handleClose"
    class="sales-order-dialog"
  >
    <el-form 
      :model="form" 
      :rules="rules" 
      ref="formRef" 
      label-width="120px"
      @submit.prevent="handleSubmit"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="订单号" prop="orderNumber">
            <el-input v-model="form.orderNumber" placeholder="请输入订单号" class="form-input" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户" prop="customerId">
            <el-select v-model="form.customerId" placeholder="请选择客户" style="width: 100%" class="form-select">
              <el-option
                v-for="customer in customerOptions"
                :key="customer.id"
                :label="customer.name"
                :value="customer.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="订单金额" prop="orderAmount">
            <el-input-number 
              v-model="form.orderAmount" 
              :min="0" 
              :precision="2" 
              style="width: 100%"
              class="form-input-number"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="订单状态" prop="orderStatus">
            <el-select v-model="form.orderStatus" placeholder="请选择订单状态" style="width: 100%" class="form-select">
              <el-option label="待付款" value="pending_payment" />
              <el-option label="已付款" value="paid" />
              <el-option label="已发货" value="shipped" />
              <el-option label="已完成" value="completed" />
              <el-option label="已取消" value="cancelled" />
              <el-option label="已退款" value="refunded" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="销售人员" prop="salesperson">
            <el-input v-model="form.salesperson" placeholder="请输入销售人员" class="form-input" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否赠品" prop="isGift">
            <el-switch v-model="form.isGift" class="form-switch" />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="发票状态" prop="invoiceStatus">
            <el-select v-model="form.invoiceStatus" placeholder="请选择发票状态" style="width: 100%" class="form-select">
              <el-option label="未开票" value="uninvoiced" />
              <el-option label="已开票" value="invoiced" />
              <el-option label="已寄送" value="sent" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="创建时间" prop="createTime">
            <el-date-picker
              v-model="form.createTime"
              type="date"
              placeholder="选择日期"
              style="width: 100%"
              value-format="YYYY-MM-DD"
              class="form-date-picker"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" class="form-textarea" />
      </el-form-item>
      
      <el-divider>订单商品</el-divider>
      <el-table :data="form.orderItems" style="width: 100%" class="order-items-table">
        <el-table-column label="商品名称" width="180">
          <template #default="scope">
            <el-input v-model="scope.row.productName" placeholder="商品名称" class="table-input" />
          </template>
        </el-table-column>
        <el-table-column label="SKU" width="120">
          <template #default="scope">
            <el-input v-model="scope.row.sku" placeholder="SKU" class="table-input" />
          </template>
        </el-table-column>
        <el-table-column label="数量" width="80">
          <template #default="scope">
            <el-input-number v-model="scope.row.quantity" :min="1" class="table-input-number" />
          </template>
        </el-table-column>
        <el-table-column label="单价" width="100">
          <template #default="scope">
            <el-input-number v-model="scope.row.unitPrice" :min="0" :precision="2" class="table-input-number" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80">
          <template #default="scope">
            <el-button @click="removeOrderItem(scope.$index)" type="danger" size="small" class="table-action-btn">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 10px;">
        <el-button @click="addOrderItem" type="primary" class="add-item-btn">添加商品</el-button>
      </div>
    </el-form>
    
    <template #footer>
      <el-button @click="handleClose" class="dialog-cancel-btn">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitting" class="dialog-submit-btn">
        {{ editingOrder ? '更新' : '保存' }}
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from '@vue/runtime-core'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

// 客户选项数据
const customerOptions = [
  { id: 1, name: '阿里巴巴集团' },
  { id: 2, name: '腾讯科技' },
  { id: 3, name: '百度公司' }
]

interface OrderItem {
  id: number
  productName: string
  sku: string
  quantity: number
  unitPrice: number
  subtotal: number
  remark: string
}

interface SalesOrder {
  id: number
  orderNumber: string
  customerId: number
  customerName: string
  orderAmount: number
  orderStatus: string
  salesperson: string
  invoiceStatus: string
  isGift: boolean
  createTime: string
  remark: string
  orderItems: OrderItem[]
}

const props = defineProps<{
  modelValue: boolean
  editingOrder: SalesOrder | null
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'submit', form: any): void
  (e: 'close'): void
}>()

const visible = computed({
  get: () => props.modelValue,
  set: (value: boolean) => emit('update:modelValue', value)
})

const formRef = ref<FormInstance>()
const submitting = ref(false)

const form = ref({
  orderNumber: '',
  customerId: null as number | null,
  orderAmount: 0,
  orderStatus: 'pending_payment',
  salesperson: '',
  invoiceStatus: 'uninvoiced',
  isGift: false,
  createTime: '',
  remark: '',
  orderItems: [] as OrderItem[]
})

const dialogTitle = computed(() => {
  return props.editingOrder ? '编辑销售订单' : '新增销售订单'
})

const rules = ref<FormRules>({
  orderNumber: [
    { required: true, message: '请输入订单号', trigger: 'blur' }
  ],
  customerId: [
    { required: true, message: '请选择客户', trigger: 'change' }
  ],
  orderAmount: [
    { required: true, message: '请输入订单金额', trigger: 'blur' }
  ],
  salesperson: [
    { required: true, message: '请输入销售人员', trigger: 'blur' }
  ]
})

// 监听编辑项变化
watch(() => props.editingOrder, (newVal: SalesOrder | null) => {
  if (newVal) {
    // 编辑模式，填充表单数据
    form.value = { 
      orderNumber: newVal.orderNumber,
      customerId: newVal.customerId,
      orderAmount: newVal.orderAmount,
      orderStatus: newVal.orderStatus,
      salesperson: newVal.salesperson,
      invoiceStatus: newVal.invoiceStatus,
      isGift: newVal.isGift,
      createTime: newVal.createTime,
      remark: newVal.remark,
      orderItems: [...newVal.orderItems]
    }
  } else {
    // 新增模式，重置表单
    form.value = {
      orderNumber: '',
      customerId: null,
      orderAmount: 0,
      orderStatus: 'pending_payment',
      salesperson: '',
      invoiceStatus: 'uninvoiced',
      isGift: false,
      createTime: '',
      remark: '',
      orderItems: []
    }
  }
}, { immediate: true })

const handleClose = () => {
  visible.value = false
  emit('close')
}

const addOrderItem = () => {
  form.value.orderItems.push({
    id: Date.now(),
    productName: '',
    sku: '',
    quantity: 1,
    unitPrice: 0,
    subtotal: 0,
    remark: ''
  })
}

const removeOrderItem = (index: number) => {
  form.value.orderItems.splice(index, 1)
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate((valid: boolean) => {
    if (valid) {
      submitting.value = true
      try {
        // 计算小计
        form.value.orderItems.forEach((item: OrderItem) => {
          item.subtotal = item.quantity * item.unitPrice
        })
        
        // 计算总金额
        form.value.orderAmount = form.value.orderItems.reduce((sum: number, item: OrderItem) => sum + item.subtotal, 0)
        
        // 如果是编辑模式，保留原始ID
        const result = props.editingOrder ? 
          { ...form.value, id: props.editingOrder.id } : 
          { ...form.value }
        
        emit('submit', result)
        handleClose()
        ElMessage.success(`${props.editingOrder ? '更新' : '保存'}成功`)
      } catch (error) {
        ElMessage.error(`${props.editingOrder ? '更新' : '保存'}失败`)
      } finally {
        submitting.value = false
      }
    }
  })
}
</script>

<style scoped>
.el-form-item {
  margin-bottom: 18px;
}

.el-divider {
  margin: 20px 0;
}

/* 表单元素悬停效果 */
.form-input:hover,
.form-select:hover,
.form-input-number:hover,
.form-date-picker:hover,
.form-textarea:hover {
  transform: translateY(-1px);
  transition: all 0.3s ease;
}

/* 开关组件特殊样式 */
.form-switch {
  transition: all 0.3s ease;
}

.form-switch:hover {
  transform: scale(1.1);
}

/* 表格输入框悬停效果 */
.table-input:hover,
.table-input-number:hover {
  transform: translateY(-1px);
  transition: all 0.3s ease;
}

/* 表格操作按钮悬停效果 */
.table-action-btn {
  transition: all 0.3s ease;
}

.table-action-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

/* 添加商品按钮悬停效果 */
.add-item-btn {
  transition: all 0.3s ease;
}

.add-item-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

/* 对话框按钮悬停效果 */
.dialog-cancel-btn,
.dialog-submit-btn {
  transition: all 0.3s ease;
}

.dialog-cancel-btn:hover,
.dialog-submit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.dialog-submit-btn {
  background-color: #409eff;
  border-color: #409eff;
}

.dialog-submit-btn:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

/* 对话框整体样式 */
.sales-order-dialog {
  transition: all 0.3s ease;
}

:deep(.sales-order-dialog .el-dialog__body) {
  padding: 20px;
}

:deep(.sales-order-dialog .el-dialog__header) {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
}

/* 表格样式优化 */
.order-items-table {
  transition: all 0.3s ease;
}

.order-items-table:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 移动端适配 */
@media (max-width: 768px) {
  .el-dialog {
    width: 95% !important;
    margin-top: 20px !important;
  }
  
  .el-row {
    flex-direction: column;
    gap: 16px;
  }
  
  .el-col {
    width: 100%;
  }
  
  .table-action-btn,
  .add-item-btn,
  .dialog-cancel-btn,
  .dialog-submit-btn {
    padding: 12px 20px;
    font-size: 14px;
  }
}
</style>